﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.MacroEngines;
using System.Xml;

namespace CoreDataTypes.RelatedLinks.RazorModel
{
    [RazorDataTypeModel("71b8ad1a-8dc2-425c-b6b8-faa158075e63")]
    public class ModelBinder : IRazorDataTypeModel
    {
        public object PropertyData;
        public int CurrentNodeId;
        public bool Init(int CurrentNodeId, string PropertyData, out object instance)
        {
            this.PropertyData = PropertyData;
            this.CurrentNodeId = CurrentNodeId;
            var links = new Links();
            if (!string.IsNullOrEmpty(PropertyData))
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(PropertyData);
                foreach (XmlNode node in doc.SelectNodes("//link"))
                {
                    links.Items.Add(new Link()
                    {
                        Title = node.SelectSingleNode("./@title").InnerText,
                        NewWindow = (node.SelectSingleNode("./@newwindow").InnerText == "1"),
                        Type = (LinkType)Enum.Parse(typeof(LinkType), node.SelectSingleNode("./@type").InnerText, true),
                        Data = node.SelectSingleNode("./@link").InnerText
                    });

                }
            }
            instance = links;
            return true;
        }
    }
}
